package ru.tomsk.autovokzal.tools.networking;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import ru.tomsk.autovokzal.tools.UnicodeReader;

/**
 * Класс для работы с пост запросами
 * 
 * @author Dolgov_Alexandr
 * 
 */
public class HTTPClient {
	/**
	 * Клиент для выполнения пост запросов
	 */
	private HttpClient httpclient;
	/**
	 * Пост запрос
	 */
	private HttpPost httppost;
	/**
	 * Пост параметры
	 */
	private List<NameValuePair> nameValuePairs;
	/**
	 * Адресс
	 */
	private String URL;

	public HTTPClient(List<NameValuePair> nameValuePairs, String uRL)
			throws UnsupportedEncodingException {
		super();
		this.nameValuePairs = nameValuePairs;
		URL = uRL;
		httppost = new HttpPost(URL);
		httpclient = new DefaultHttpClient();
		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	}

	public HTTPClient(String uRL) throws UnsupportedEncodingException {
		super();
		URL = uRL;
		httpclient = new DefaultHttpClient();
		httppost = new HttpPost(URL);
	}

	/**
	 * Полчает ответ от сервера
	 * 
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public HttpResponse getResponce() throws ClientProtocolException,
			IOException {
		return httpclient.execute(httppost);
	}

	public List<NameValuePair> getNameValuePairs() {
		return nameValuePairs;
	}

	public void setNameValuePairs(List<NameValuePair> nameValuePairs) {
		this.nameValuePairs = nameValuePairs;
	}

	public String getURL() {
		return URL;
	}

	public void setURL(String uRL) {
		URL = uRL;
	}

	public void setDefaultHeader() {
		httppost.setHeader("Content-Type",
				"application/x-www-form-urlencoded");
//		httppost.setHeader("Accept", "*/*");
//		httppost.setHeader("Accept-Encoding", "gzip,deflate,sdch");
//		httppost.setHeader("Accept-Language",
//				"ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
//		httppost.setHeader("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.3");
	}

	public void setHeader(String name, String value) {
		httppost.setHeader(name, value);
	}

	public void setEntity(HttpEntity entity) {
		httppost.setEntity(entity);
	}

	public String getResponseBody(HttpEntity entity) throws IOException,
			ParseException {
		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		InputStream instream = entity.getContent();
		if (instream == null) {
			return "";
		}
		if (entity.getContentLength() > Integer.MAX_VALUE) {
			throw new IllegalArgumentException(
					"HTTP entity too large to be buffered in memory");
		}
		String charset = getContentCharSet(entity);
		if (charset == null) {
			charset = HTTP.DEFAULT_CONTENT_CHARSET;
		}
		Reader reader = new UnicodeReader(instream, charset);

		StringBuilder buffer = new StringBuilder();
		try {
			char[] tmp = new char[1024];
			int l;
			while ((l = reader.read(tmp)) != -1) {
				buffer.append(tmp, 0, l);
			}
		} finally {
			reader.close();
		}
		return buffer.toString();
	}

	public String getContentCharSet(final HttpEntity entity)
			throws ParseException {
		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) {
					charset = param.getValue();
				}
			}
		}
		return charset;

	}

}
